package com.pl.service;

import com.pl.v.OnvifCredentials;
import com.pl.v.OnvifDevice;
import com.pl.v.OnvifUtils;
import lombok.extern.slf4j.Slf4j;
import org.onvif.ver10.media.wsdl.Media;
import org.onvif.ver10.schema.Profile;
import org.springframework.stereotype.Service;

import javax.xml.soap.SOAPException;
import java.net.ConnectException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author shent
 */
@Service
@Slf4j
public class VideoService {

    public Map<String, Object> getUrl(Long deviceId) throws MalformedURLException, SOAPException, ConnectException {
        HashMap<String, Object> result = new HashMap(2);
        OnvifCredentials credentials = new OnvifCredentials("192.168.11.200", "admin", "admin12345", "");
//        OnvifCredentials credentials = new OnvifCredentials("192.168.11.109", "admin", "admin888", "");
        URL url = credentials.getHost().startsWith("http")
                ? new URL(credentials.getHost())
                : new URL("http://" + credentials.getHost());
        OnvifDevice device = new OnvifDevice(url, credentials.getUser(), credentials.getPassword());
        Media media = device.getMedia();
        media.getVideoSources();
        List<Profile> profiles = media.getProfiles();
//        log.info("Media Profiles: " + profiles.size());
//        for (Profile profile : profiles) {
//            String profileToken = profile.getToken();
//            String rtsp = device.getStreamUri(profileToken);
//            log.info("\tProfile: " + profile.getName() + " token=" + profile.getToken());
//            log.info("\t\tstream: " + rtsp);
//            log.info("\t\tsnapshot: " + device.getSnapshotUri(profileToken));
//            log.info("\t\tdetails:" + OnvifUtils.format(profile));
//        }
        String profileToken = profiles.get(0).getToken();
        String rtsp = device.getStreamUri(profileToken);
        result.put("image", device.getSnapshotUri(profileToken));
        String flv = ConvertRtspToFlv(rtsp);
        result.put("url", flv==null?rtsp:flv);
        return result;
    }

    private String ConvertRtspToFlv(String rtsp) {

        return null;
    }
}
